package cn.dakaqi.services.user.impl;

import cn.dakaqi.dao.user.VolunteerDao;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.LogService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.Identities;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/13.
 */
@Component(value = "volunteerService")
@Transactional
public class VolunteerServiceImpl implements VolunteerService
{
    @Autowired
    VolunteerDao volunteerDao;
    @Autowired
    LogService logService;
    private void saveLog(String message)
    {
        logService.save(2000,message);
    }
    @Override
    public Volunteer saveVolunteer(Volunteer volunteer) throws ServiceRuntimeException
    {
        if (null == volunteer)
            throw new ServiceRuntimeException("志愿者数据无效");

        return this.volunteerDao.save(volunteer);
    }

    @Override
    public void updateVolunteer(Volunteer volunteer) throws ServiceRuntimeException
    {
        if (null == volunteer)
            throw new ServiceRuntimeException("志愿者数据无效");

        //从身份证中取出性别、生是
        volunteer.setSex(getSexFromCardNO(volunteer.getCardNO()));
        volunteer.setBirthDay(getBirthFromCardNO(volunteer.getCardNO()));
        this.volunteerDao.save(volunteer);
    }

    @Override
    public void updateVolunteer(String jsonData) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(jsonData);
        Volunteer tempVolunteer = JSON.toJavaObject(jsonObject,Volunteer.class);
        tempVolunteer.setQQ(jsonObject.getString("QQ"));
        Volunteer volunteer = this.findByMemberCode(tempVolunteer.getMemberCode());
        if(null == volunteer)
        {
            String message = "志愿者信息无效";
            throw new ServiceRuntimeException(message);
        }
        Volunteer v1 = this.findByCardNO(tempVolunteer.getCardNO());
        if(null != v1 && !v1.getMemberCode().equals(tempVolunteer.getMemberCode()))
        {
            String message = "证件号已被使用";
            throw new ServiceRuntimeException(message);
        }
        this.updateVolunteer(tempVolunteer, volunteer);
    }

    @Override
    public void updateVolunteer(Volunteer tempVolunteer, Volunteer targetVolunteer) throws ServiceRuntimeException
    {
        if (null == tempVolunteer || null == targetVolunteer)
            throw new ServiceRuntimeException("待更新的志愿者数据无效");
        targetVolunteer.setNickName(tempVolunteer.getNickName());
        targetVolunteer.setRealName(tempVolunteer.getRealName());
        if (targetVolunteer.getLocked() == DKQConstant.MEMBER_LOCK_0)
        {
            targetVolunteer.setCardType(tempVolunteer.getCardType());
            targetVolunteer.setCardNO(tempVolunteer.getCardNO());
            if (tempVolunteer.getCardType().equals("CID"))
            {
                //从身份证中取出性别、生是
                targetVolunteer.setSex(getSexFromCardNO(tempVolunteer.getCardNO()));
                targetVolunteer.setBirthDay(getBirthFromCardNO(tempVolunteer.getCardNO()));
            }
        }
        targetVolunteer.setResidenceAddress(tempVolunteer.getResidenceAddress());
        String address[] = tempVolunteer.getResidenceAddress().split("-");
        if(address.length == 3)
        {
            targetVolunteer.setProvince(address[0]);
            targetVolunteer.setCity(address[1]);
            targetVolunteer.setDistrict(address[2]);
        }
        else if(address.length == 2)
        {
            targetVolunteer.setProvince(address[0]);
            targetVolunteer.setCity(address[0]);
            targetVolunteer.setDistrict(address[1]);
        }
        targetVolunteer.setJob(tempVolunteer.getJob());
        targetVolunteer.setServiceField(tempVolunteer.getServiceField());
        targetVolunteer.setSkill(tempVolunteer.getSkill());
        targetVolunteer.setQQ(tempVolunteer.getQQ());
        targetVolunteer.setSign(tempVolunteer.getSign());
        targetVolunteer.setWeChat(tempVolunteer.getWeChat());
        targetVolunteer.setIsFinished(DKQConstant.USER_IS_FINISH_YES);
        updateVolunteer(targetVolunteer);
    }

    @Override
    public void updatePortrait(String param) throws ServiceRuntimeException
    {
        JSONObject jsonObject = JSON.parseObject(param);
        String memberCode = jsonObject.getString("memberCode");
        String portrait = jsonObject.getString("portrait");
        if(StringUtils.isBlank(memberCode))
            throw new ServiceRuntimeException("志愿者编号不能为空");
        if(StringUtils.isBlank(portrait))
            throw new ServiceRuntimeException("头像不能为空");
        this.updatePortrait(memberCode, portrait);
    }

    @Override
    public void updatePortrait(String memberCode, String url) throws ServiceRuntimeException
    {
        Volunteer volunteer = this.findByMemberCode(memberCode);
        if(null == volunteer)
            throw new ServiceRuntimeException("志愿者不存在");
        if(volunteer.getIsFinished() == DKQConstant.USER_IS_FINISH_NO)
            throw new ServiceRuntimeException("请先完善个人资料");
        volunteer.setHeadUrl(url);
        this.updateVolunteer(volunteer);
    }

    private String getBirthFromCardNO(String icard)
    {
        int len = icard.length();
        StringBuilder ymd = new StringBuilder();
        switch (len)
        {
            case 15:

                ymd.append("19").append(icard.substring(6, 12));
                break;
            case 18:
                ymd.append(icard.substring(6, 14));
                break;
            default:
                return "2010-01-01";
        }
        return ymd.substring(0, 4) + "-" + ymd.substring(4, 6) + "-" + ymd.substring(6, 8);
    }

    private String getSexFromCardNO(String icard)
    {
        int len = icard.length();
        String sex = "男";
        switch (len)
        {
            case 15:
                //String birth1 = icard.substring(6, 12);
                sex = icard.substring(14, 15);
                if (Integer.parseInt(sex) % 2 == 0)
                {
                    sex = "女";
                } else
                {
                    sex = "男";

                }
                break;
            case 18:
                //String birth2 = icard.substring(6, 14);
                sex = icard.substring(16, 17);
                if (Integer.parseInt(sex) % 2 == 0)
                {
                    sex = "女";
                } else
                {
                    sex = "男";

                }
                break;
        }
        return sex;
    }

    @Override
    public Volunteer findByVolunteerCode(String volunteerCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("volunteerCode", new SearchFilter("volunteerCode", SearchFilter.Operator.EQ, volunteerCode));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        List<Volunteer> list = this.volunteerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public Volunteer findByMemberCode(String memberCode) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("memberCode", new SearchFilter("memberCode", SearchFilter.Operator.EQ, memberCode));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        List<Volunteer> list = this.volunteerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public Volunteer findByUserId(Long userId) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("userId", new SearchFilter("userId", SearchFilter.Operator.EQ, userId));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        List<Volunteer> list = this.volunteerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public Volunteer findOne(Long id) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("id", new SearchFilter("id", SearchFilter.Operator.EQ, id));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        List<Volunteer> list = this.volunteerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public Page<Volunteer> findByLocked(int locked, Pageable pageRequest) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("locked", new SearchFilter("locked", SearchFilter.Operator.EQ, locked));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        return this.volunteerDao.findAll(spec,pageRequest);
    }

    @Override
    public void updateMobile(String oldMobile, String newMobile)
    {
        Volunteer volunteer = volunteerDao.findByMobile(oldMobile);
        if(null != volunteer)
        {
            volunteer.setMobile(newMobile);
            this.updateVolunteer(volunteer);
        }
    }

    @Override
    public Volunteer findByCardNO(String cardNO) throws ServiceRuntimeException
    {
        Map<String, SearchFilter> filters = Maps.newHashMap();
        filters.put("cardNO", new SearchFilter("cardNO", SearchFilter.Operator.EQ, cardNO));
        Specification<Volunteer> spec = DynamicSpecifications.bySearchFilter(filters.values(), Volunteer.class);
        List<Volunteer> list = this.volunteerDao.findAll(spec);
        if(null == list || list.size() ==0)
            return null;
        else
            return list.get(0);
    }

    @Override
    public void saveVolunteer(Volunteer volunteer, String groupCode) throws ServiceRuntimeException
    {
//        this.volunteerDao.save(volunteer);
//
//        //将当前志愿者加当前社团
//        GroupVolunteer groupVolunteer = new GroupVolunteer();
//        groupVolunteer.setVolunteer(volunteer);
//        Group group = this.groupService.findByGroupCode(groupCode);
//        groupVolunteer.setGroup(group);
//        groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
//        groupVolunteer.setStatus(DKQConstant.APPLY_STATUS_OK);
//        groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
//        groupVolunteer.setDelStatus(DKQConstant.DEL_NO);
//        this.groupVolunteerService.save(groupVolunteer);
    }

    private String createVolunteerCode(String province,String city,String district)
    {
        StringBuffer sb = new StringBuffer();
        province = "江苏省";
        String code = this.volunteerDao.queryProvinceCode(province);
        sb.append("V");
        sb.append(code);
        sb.append(DateUtil.currentDateStringTrim());
        String targetStr[] = Identities.uuid().split("-");
        sb.append(targetStr[1].toUpperCase());
        return sb.toString();
    }
}
